from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.spus import SPUGoodsSerializer, SPUBrandsSerializer, CategorysSerializer
from goods.models import SPU,Brand, GoodsCategory, SKU
from meiduo_admin.utils import UserPageNum
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from meiduo_admin.serializers.images import SKUSerializer


class SPUGoodsView(ModelViewSet):
    """
    SPU表的增删改查
    """
    serializer_class = SPUGoodsSerializer
    queryset = SPU.objects.all()
    pagination_class = UserPageNum


class SPUSView(ModelViewSet):
    """
    spu表的增删改查
    """
    serializer_class = SPUBrandsSerializer
    queryset = SPU.objects.all()
    pagination_class = UserPageNum

    def brand(self, request):
        data = Brand.objects.all()
        ser = SPUBrandsSerializer(data, many=True)
        return Response(ser.data)

    def channel(self, reuqest):
        data = GoodsCategory.objects.filter(parent=None)
        ser = CategorysSerializer(data, many=True)
        return Response(ser.data)

    def channels(self, request, pk):
        data = GoodsCategory.objects.filter(parent_id=pk)
        ser = CategorysSerializer(data, many=True)
        return Response(ser.data)

    def image(self, request):
        """
        保存图片
        :param reuqest:
        :return:
        """
        data = request.FILES.get('image')
        if data is None:
            return Response(status=500)

        client = Fdfs_client(settings.FASTDFS_PATH)
        res = client.upload_by_buffer(data.read())
        if res['Status'] != 'Upload successed.':
            return Response({'error':'上传失败'},status=501)
        image_url = res['Remote file_id']

        return Response(
            {
                'image_url':settings.FASTDFS_PATH + image_url
            },
            status=201
        )


class SKUGoodsView(ModelViewSet):
    serializer_class = SKUSerializer
    pagination_class = UserPageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword == '' or keyword is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name=keyword)
